package com.example.demo.controller;

import com.port.fee.common.Result;
import com.port.fee.dao.CargoMapper;
import com.port.fee.dao.CustomerMapper;
import com.port.fee.dao.FeeRecordMapper;
import com.port.fee.service.CargoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 报表分析控制器
 */
@RestController
@RequestMapping("/report")
@Tag(name = "报表分析", description = "报表统计相关接口")
public class ReportController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReportController.class);

    @Autowired
    private CargoMapper cargoMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private FeeRecordMapper feeRecordMapper;

    @Autowired
    private CargoService cargoService;

    /**
     * 按月份统计货物流量
     */
    @GetMapping("/cargo-flow/monthly")
    @Operation(summary = "按月份统计货物流量", description = "按月份统计货物流量")
    public Result<List<Map<String, Object>>> cargoFlowByMonth(@RequestParam(required = false) Integer year) {
        try {
            // 如果没有指定年份，则使用当前年份
            if (year == null) {
                year = Calendar.getInstance().get(Calendar.YEAR);
            }

            List<Map<String, Object>> result = cargoMapper.countCargoFlowByMonth(year);
            
            // 确保所有12个月都有数据
            Map<Integer, Map<String, Object>> monthDataMap = new HashMap<>();
            for (Map<String, Object> monthData : result) {
                Integer month = (Integer) monthData.get("month");
                monthDataMap.put(month, monthData);
            }
            
            List<Map<String, Object>> completeResult = new ArrayList<>();
            for (int month = 1; month <= 12; month++) {
                if (monthDataMap.containsKey(month)) {
                    completeResult.add(monthDataMap.get(month));
                } else {
                    Map<String, Object> emptyMonthData = new HashMap<>();
                    emptyMonthData.put("month", month);
                    emptyMonthData.put("inCount", 0);
                    emptyMonthData.put("outCount", 0);
                    completeResult.add(emptyMonthData);
                }
            }

            return Result.success(completeResult);
        } catch (Exception e) {
            LOGGER.error("获取月度货物流量统计异常: ", e);
            return Result.failed("获取月度货物流量统计失败: " + e.getMessage());
        }
    }

    /**
     * 按货物类型统计
     */
    @GetMapping("/cargo/by-type")
    @Operation(summary = "按货物类型统计", description = "按货物类型统计数量和比例")
    public Result<List<Map<String, Object>>> cargoStatsByType() {
        try {
            List<Map<String, Object>> result = cargoMapper.countCargoByType();
            
            // 计算总数和百分比
            int total = 0;
            for (Map<String, Object> item : result) {
                total += ((Number) item.get("count")).intValue();
            }
            
            // 添加百分比字段
            for (Map<String, Object> item : result) {
                int count = ((Number) item.get("count")).intValue();
                double percentage = total > 0 ? Math.round((double) count / total * 100) : 0;
                item.put("percentage", percentage);
            }

            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取货物类型统计异常: ", e);
            return Result.failed("获取货物类型统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取系统统计数据
     */
    @GetMapping("/system-stats")
    @Operation(summary = "获取系统统计数据", description = "获取系统统计数据，如货物总数、客户总数等")
    public Result<Map<String, Object>> getSystemStats() {
        try {
            Map<String, Object> stats = new HashMap<>();

            // 货物总数
            Long totalCargoCount = cargoMapper.selectCount(null);
            stats.put("totalCargo", totalCargoCount);

            // 在港货物数
            Map<String, Object> inPortMap = cargoMapper.countCargoByStatus(1);
            Integer inPortCargo = inPortMap != null ? ((Number) inPortMap.get("count")).intValue() : 0;
            stats.put("inPortCargo", inPortCargo);

            // 客户总数
            Long totalCustomersCount = customerMapper.selectCount(null);
            stats.put("totalCustomers", totalCustomersCount);

            // 总收入
            BigDecimal totalIncome = feeRecordMapper.getTotalPaidAmount();
            stats.put("totalIncome", totalIncome != null ? totalIncome : BigDecimal.ZERO);

            return Result.success(stats);
        } catch (Exception e) {
            LOGGER.error("获取系统统计数据异常: ", e);
            return Result.failed("获取系统统计数据失败: " + e.getMessage());
        }
    }
}